package com.lindroy.androidplayer.ui.knowledge

import android.os.Bundle
import androidx.fragment.app.viewModels
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.base.BaseLazyFragment
import com.lindroy.androidplayer.extensions.*
import com.lindroy.androidplayer.ui.adapter.KnowledgeIndexAdapter
import com.lindroy.androidplayer.viewmodel.KnowledgeViewModel
import com.lindroy.lib_utils.extensions.isNetworkConnect
import kotlinx.android.synthetic.main.fragment_knowledge_index.*

/**
 * @author Lin
 * @date 2021/4/28
 * @function 首页-体系
 */
class KnowledgeIndexFragment(override val layoutId: Int = R.layout.fragment_knowledge_index) :
    BaseLazyFragment() {

    private val knowledgeViewModel: KnowledgeViewModel by viewModels()

    private val adapter by lazy { KnowledgeIndexAdapter() }

    override fun initView() {
        refreshHeader.initColor()
        rvKnowledgeIndex.setLineDivider()
        rvKnowledgeIndex.adapter = adapter
    }

    override fun lazyLoad() {
        reqKnowledgeTree(true)
    }

    override fun initListener() {
        knowledgeViewModel.knowledgeState.observe(this) {resultState->
            parseState(resultState,onError = {
                isNetworkConnect.yes {
                    stateLayout.showError()
                }.no {
                    stateLayout.showNoNetwork()
                }
            }) {
                refreshLayout.finishRefresh()
                stateLayout.showContent()
                adapter.setList(it)
            }
        }
        refreshLayout.setOnRefreshListener {
            reqKnowledgeTree(false)
        }
    }

    private fun reqKnowledgeTree(showLoading:Boolean){
        showLoading.yes {
            stateLayout.showLoading()
        }
        knowledgeViewModel.reqKnowledgeTree()
    }

    override fun initClick() {
        stateLayout.setOnViewsClickListener { state, view ->
            reqKnowledgeTree(true)
        }
    }

    companion object {
        @JvmStatic
        fun newInstance() =
            KnowledgeIndexFragment().apply {
                arguments = Bundle().apply {
                }
            }
    }
}